/*
 * Copyright (C) 2009, 2010 M. Homs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.homs.jsunit.runner;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.homs.jsunit.exception.JavascriptException;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

public class RhinoRunner implements Runner {

	protected Context cx;
	protected Scriptable scope;

	public RhinoRunner() {
		super();
		cx = new ContextFactory().enterContext();
		// optimization=false, necessari per executar Continuations
		cx.setOptimizationLevel(-1);

		scope = cx.initStandardObjects();

		final Object wrappedOut = Context.javaToJS(System.out, scope);
		ScriptableObject.putProperty(scope, "out", wrappedOut);

		this.eval("function print(o){out.print(o);};");
		this.eval("function println(o){out.println(o);};");
	}

	public final Object eval(final String expression) {
		return cx.evaluateString(scope, expression, "user-expression", 1, null);
	}

	public Object evalScript(final String scriptName) {
		final BufferedReader br;
		try {
			final InputStream url = Thread.currentThread().getContextClassLoader().getResourceAsStream(
					scriptName);
			br = new BufferedReader(new InputStreamReader(url));
		} catch (final Exception e) {
			throw new JavascriptException("error opening script: " + scriptName, e);
		}
		try {
			return cx.evaluateReader(scope, br, scriptName, 1, null);
		} catch (final Exception e) {
			throw new JavascriptException("error evaluating script: " + scriptName, e);
		}
	}

	public void close() {
		Context.exit();
	}

	public Context getContext() {
		return cx;
	}

	public Scriptable getScope() {
		return scope;
	}

	public Object get(final String varName) {
		return this.scope.get(varName, this.scope);
	}

	public Runner put(final String varName, final Object value) {
		this.scope.put(varName, this.scope, value);
		return this;
	}

}
